package com.flyim.web.controller.system;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flyim.common.core.domain.AjaxResult;
import com.flyim.common.core.domain.entity.SysUser;
import com.flyim.common.utils.ShiroUtils;
import com.flyim.framework.netty.ChannelManager;
import com.flyim.system.domain.vo.ImUserVo;
import com.flyim.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

import static com.flyim.common.utils.ShiroUtils.getSysUser;

/**
 * @Package: com.flyim.web.controller.system
 * @ClassName: ImController.java
 * @Description: IM
 * @author: zhengxiaolong
 * @date: 2025/2/21 14:55
 */
@Controller
@RequestMapping("/system/im")
public class ImController {
    private final String prefix = "system/im";

    @Autowired
    private ISysUserService userService;

    @GetMapping
    public String index(ModelMap mmap) throws JsonProcessingException {
//      获取当前用户
        SysUser user = getSysUser();
        mmap.put("loginUser", user);
        mmap.put("userList", getImUserList());
        mmap.addAttribute("currentUserId", ShiroUtils.getUserId());
        mmap.addAttribute("currentUserName", ShiroUtils.getSysUser().getUserName());
        return prefix + "/im";
    }

    @PostMapping("/userList")
    @ResponseBody
    public AjaxResult getUserList() {
        List<ImUserVo> imUserList = getImUserList();
        return AjaxResult.success(imUserList);
    }

    public List<ImUserVo> getImUserList() {
        // 获取所有用户
        List<SysUser> users = userService.selectUserList(new SysUser());
        // 获取在线用户
        Set<String> onlineUsers = ChannelManager.getOnlineUsers();

        // 构建返回数据
        List<ImUserVo> result = new ArrayList<>();
        for (SysUser user : users) {
            ImUserVo userInfo = ImUserVo.builder()
                    .userId(user.getUserId().toString())
                    .userName(user.getUserName())
                    .userAvatar(user.getAvatar())
                    .online(onlineUsers.contains(user.getUserId().toString()))
                    .build();
            result.add(userInfo);
        }
        return result;
    }
}